<template>
  <div class="dashboard-container">
    <github-corner class="github-corner"/>

    <el-card shadow="never">
      <el-row justify="space-between">
        <el-col :span="18" :xs="24">
          <div class="flex h-full items-center">
            <img
                class="w-20 h-20 mr-5 rounded-full"
                :src="user.avatar"
            />
            <div>
              <p>{{ user.userinfo.username }}</p>
              <p class="text-sm text-gray">
                今日天气晴朗，气温在15℃至25℃之间，东南风。
              </p>
            </div>
          </div>
        </el-col>

        <el-col :span="6" :xs="24">
          <div class="flex h-full items-center justify-around">
            <el-statistic
                v-for="item in statisticData"
                :key="item.key"
                :value="item.value"
            >
              <template #title>
                <div class="flex items-center">
                  <svg-icon :icon-class="item.iconClass" size="20px"/>
                  <span class="text-[16px] ml-1">{{ item.title }}</span>
                </div>
              </template>
              <template v-if="item.suffix" #suffix>/100</template>
            </el-statistic>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <div style="margin-top: 20px;display: flex;align-items: center">
      <el-card style="width: 50%;margin-right: 20px">
        <div>个人资料</div>
        <div style="display: flex;align-items: center;justify-content: center;margin: 10px 0">
          <el-avatar :size="120" :src="user.avatar"/>
        </div>
        <p style="text-align: center;font-size: 18px">{{ user.userinfo.username }}</p>
        <el-form label-width="auto">
          <el-form-item label="用户名：">
            <el-input v-model="user.userinfo.nickname" disabled/>
          </el-form-item>
          <el-form-item label="手机号：">
            <el-input disabled/>
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="user.userinfo.nickname" disabled/>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card style="width: 50%;">
        <el-tabs type="border-card">
          <el-tab-pane label="操作日志">
            <el-table border style="width: 100%">
              <el-table-column prop="ID" label="ID"/>
              <el-table-column prop="title" label="标题"/>
              <el-table-column prop="content" label="内容"/>
              <el-table-column prop="ur" label="链接"/>
              <el-table-column prop="createdby" label="上传人"/>
              <el-table-column prop="createtime" label="创建时间"/>
              <el-table-column prop="updatetime" label="更新时间"/>
            </el-table>
          </el-tab-pane>

        </el-tabs>
      </el-card>
    </div>


    <NoticeDetail ref="noticeDetailRef"/>
  </div>
</template>

<script setup lang="ts">
import {getUserInfo} from "@/utils/auth";

defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import VisitTrend from "./components/VisitTrend.vue";

import WebSocketManager from "@/utils/websocket";
import router from "@/router";

import {useUserStore} from "@/store/modules/user";
import StatsAPI, {VisitStatsVO} from "@/api/system/log";
import NoticeAPI, {NoticePageVO} from "@/api/system/notice";

const noticeDetailRef = ref();

const userStore = useUserStore();
const date: Date = new Date();
const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return "上午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 12 && hours < 18) {
    return "下午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 18 && hours < 24) {
    return "晚上好，" + userStore.userInfo.nickname + "！";
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

const user = JSON.parse(getUserInfo())

// 右上角数量
const statisticData = ref([
  {
    value: 99,
    iconClass: "message",
    title: "消息",
    key: "message",
  },
  {
    value: 50,
    iconClass: "todo",
    title: "待办",
    suffix: "/100",
    key: "upcoming",
  },
  {
    value: 10,
    iconClass: "project",
    title: "项目",
    key: "project",
  },
]);

const onlineUserCount = ref(0);

const visitStatsLoading = ref(true);
const visitStatsList = ref<VisitStats[] | null>(Array(3).fill({}));

interface VisitStats {
  title: string;
  icon: string;
  tagType: "primary" | "success" | "warning";
  growthRate: number;
  // 粒度
  granularity: string;
  // 今日数量
  todayCount: number;
  totalCount: number;
}

// 加载访问统计数据
const loadVisitStatsData = async () => {
  // const list: VisitStatsVO[] = await StatsAPI.getVisitStats();
  //
  // if (list) {
  //   const tagTypes: ("primary" | "success" | "warning")[] = [
  //     "primary",
  //     "success",
  //     "warning",
  //   ];
  //   const transformedList: VisitStats[] = list.map((item, index) => ({
  //     title: item.title,
  //     icon: getVisitStatsIcon(item.type),
  //     tagType: tagTypes[index % tagTypes.length],
  //     growthRate: item.growthRate,
  //     granularity: "日",
  //     todayCount: item.todayCount,
  //     totalCount: item.totalCount,
  //   }));
  //   visitStatsList.value = transformedList;
  //   visitStatsLoading.value = false;
  // }
};

/** 格式化增长率 */
const formatGrowthRate = (growthRate: number): string => {
  if (growthRate === 0) {
    return "-";
  }

  const formattedRate = Math.abs(growthRate * 100)
      .toFixed(2)
      .replace(/\.?0+$/, "");
  return formattedRate + "%";
};

/** 获取增长率文本颜色类 */
const getGrowthRateClass = (growthRate: number): string => {
  if (growthRate > 0) {
    return "color-[--el-color-danger]";
  } else if (growthRate < 0) {
    return "color-[--el-color-success]";
  } else {
    return "color-[--el-color-info]";
  }
};

/** 获取访问统计图标 */
const getVisitStatsIcon = (type: string) => {
  switch (type) {
    case "pv":
      return "pv";
    case "uv":
      return "uv";
    case "ip":
      return "ip";
    default:
      return "pv";
  }
};

const notices = ref<NoticePageVO[]>([]);

// 查看更多
function viewMoreNotice() {
  router.push({path: "/myNotice"});
}

// 阅读通知公告
function viewNoticeDetail(id: string) {
  noticeDetailRef.value.openNotice(id);
}

onMounted(() => {
  // loadVisitStatsData();

  // // 获取我的通知公告
  // NoticeAPI.getMyNoticePage({ pageNum: 1, pageSize: 10 }).then((data) => {
  //   notices.value = data.list;
  // });
  //
  // WebSocketManager.subscribeToTopic("/topic/onlineUserCount", (data) => {
  //   console.log("收到在线用户数量：", data);
  //   onlineUserCount.value = JSON.parse(data);
  // });
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }
}
</style>
